<template>
  <div class="container">
    <el-alert v-if="alertMessage" :title="alertMessage" :type="alertType" show-icon :closable="false" />
    <el-card class="header-card">
      <div class="header">
        <el-row :gutter="20">
          <!-- <el-col :span="4">
            <el-form-item label="年度">
              <el-input v-model="form.year" @change="updateTableData" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="责任者">
              <el-input v-model="form.responsibleParty" />
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="4">
            <el-form-item label="单位">
              <el-input v-model="form.socialSecurityUnit" />
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="4">
            <el-form-item label="案件编号">
              <el-input v-model="form.caseId" @change="updateTableData" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="盒号">
              <el-input v-model="form.boxId" @change="updateTableData" />
            </el-form-item>
          </el-col> -->
          <el-col :span="4">
            <el-upload class="upload-demo" action="" :auto-upload="false" :show-file-list="false"
              :on-change="handleExcelImport" accept=".xlsx,.xls">
              <el-button type="primary">导入Excel文件</el-button>
            </el-upload>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <el-card class="table-card" v-show="activeSheet">
      <el-tabs v-model="activeSheet" @tab-click="handleClick">
        <el-tab-pane v-for="(data, sheetName) in sheetData" :key="sheetName" :label="sheetName" :name="sheetName">
          <div class="table-header">
            <el-form :inline="true" :model="searchForm" class="demo-form-inline">
              <el-form-item label="姓名">
                <el-input v-model="searchForm.searchName" placeholder="输入名字自动筛选" clearable />
              </el-form-item>
              <el-form-item label="身份证号">
                <el-input v-model="searchForm.searchIdCard" placeholder="输入身份证号自动过滤" clearable />
              </el-form-item>
              <span class="tips">{{ `已查询到${getFilteredCount(sheetName)}条数据` }}</span>
            </el-form>

            <div class="table-actions">
              <el-checkbox v-model="sortByBox" @change="toggleSort">
                按盒号页号排序
              </el-checkbox>
              <el-button type="primary" @click="doExportExcel">导出数据</el-button>
            </div>
          </div>
          <el-table :data="getPagedData(sheetName)" border style="width: 100%">
            <el-table-column prop="caseNumber" label="案件编号">
              <template #default="{ row, $index }">
                <el-input v-model="row.caseNumber" @keydown.enter.native="handleInputEnter($index, 0, $event)"
                  :ref="(el: any) => setInputRef(el, $index, 0)" />
              </template>
            </el-table-column>
            <el-table-column prop="boxNumber" label="盒号">
              <template #default="{ row, $index }">
                <el-input v-model="row.boxNumber" @keydown.enter.native="handleInputEnter($index, 1, $event)"
                  :ref="(el: any) => setInputRef(el, $index, 1)" />
              </template>
            </el-table-column>
            <el-table-column prop="name" label="姓名">
              <template #default="{ row, $index }">
                <el-input v-model="row.name" @keydown.enter.native="handleInputEnter($index, 2, $event)"
                  :ref="(el: any) => setInputRef(el, $index, 2)" />
              </template>
            </el-table-column>
            <el-table-column prop="idCard" label="身份证">
              <template #default="{ row, $index }">
                <el-input v-model="row.idCard" @keydown.enter.native="handleInputEnter($index, 3, $event)"
                  :ref="(el: any) => setInputRef(el, $index, 3)" />
              </template>
            </el-table-column>
            <el-table-column prop="creationDate" label="日期">
              <template #default="{ row, $index }">
                <el-input v-model="row.creationDate" @keydown.enter.native="handleInputEnter($index, 4, $event)"
                  :ref="(el: any) => setInputRef(el, $index, 4)" />
              </template>
            </el-table-column>
            <el-table-column prop="pageNumber" label="页号">
              <template #default="{ row, $index }">
                <el-input v-model="row.pageNumber" type="number"
                  @keydown.enter.native="handleInputEnter($index, 5, $event)"
                  :ref="(el: any) => setInputRef(el, $index, 5)" />
              </template>
            </el-table-column>
            <el-table-column prop="itemNumber" label="件号">
              <template #default="{ row, $index }">
                <el-input v-model="row.itemNumber" type="number"
                  @keydown.enter.native="handleInputEnter($index, 6, $event)"
                  :ref="(el: any) => setInputRef(el, $index, 6)" />
              </template>
            </el-table-column>
            <el-table-column prop="socialSecurityUnit" label="社保单位">
              <template #default="{ row, $index }">
                <el-input v-model="row.socialSecurityUnit" @keydown.enter.native="handleInputEnter($index, 7, $event)"
                  :ref="(el: any) => setInputRef(el, $index, 7)" />
              </template>
            </el-table-column>
            <el-table-column prop="responsibleParty" label="责任人">
              <template #default="{ row, $index }">
                <el-input v-model="row.responsibleParty" @keydown.enter.native="handleInputEnter($index, 8, $event)"
                  :ref="(el: any) => setInputRef(el, $index, 8)" />
              </template>
            </el-table-column>
            <el-table-column prop="note" label="备注">
              <template #default="{ row, $index }">
                <el-input v-model="row.note" @keydown.enter.native="handleInputEnter($index, 9, $event)"
                  :ref="(el: any) => setInputRef(el, $index, 9)" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button size="small" type="danger" @click="handleDelete(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="demo-pagination-block" v-if="getFilteredCount(sheetName) > 0">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]" layout="sizes, prev, pager, next" :total="getFilteredCount(sheetName)"
              @size-change="handleSizeChange" @current-change="handleCurrentChange" />
          </div>
          <br>
          <span class="tips">{{ getTableLength(sheetName) }}</span>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: 'ExcelImport'
})
import { ref, computed, nextTick } from 'vue'
import { ElMessage, TabsPaneContext } from 'element-plus'
import { saveAs } from 'file-saver'
import ExcelJS from 'exceljs'
import { postBatchMedicalRecords } from '@/api/medicalInsurance'

interface FormData {
  // year: string
  // responsibleParty: string
  // socialSecurityUnit: string
  // caseId: string
  // boxId: string
}

interface TableRow {
  index: number
  title: string
  documentNumber: string
  socialSecurityCode: string
  socialSecurityUnit: string
  otherId: string
  responsibleParty: string
  caseNumber: string
  boxNumber: string
  name: string
  idCard: string
  creationDate: string
  pageNumber: string
  pageCount: string
  township: string
  hospital: string
  itemNumber: string
  note: string
  operatorId?: string | null
}

// 表单数据
const form = ref<FormData>({
  // year: new Date().getFullYear().toString(),
  // responsibleParty: '',
  // socialSecurityUnit: '',
  // caseId: '',
  // boxId: ''
})

const filterCount = ref('')

// 表格数据
const sheetData = ref<Record<string, TableRow[]>>({})
const activeSheet = ref('')
const currentPage = ref(1)
const tableLength = ref(0)
const pageSize = ref(50) // 每页显示50条

const searchForm = ref({
  searchName: '',
  searchIdCard: ''
})

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
}

// 排序相关
const sortByBox = ref(false)

// 提示信息
const alertMessage = ref('')
const alertType = ref<'success' | 'error'>('success')

// 输入框引用存储
const inputRefs = ref<Record<number, Record<number, any>>>({})

// 设置输入框引用
const setInputRef = (el: any, rowIndex: number, colIndex: number) => {
  if (!el) return
  if (!inputRefs.value[rowIndex]) {
    inputRefs.value[rowIndex] = {}
  }
  inputRefs.value[rowIndex][colIndex] = el
}

// 处理回车事件
const handleInputEnter = (rowIndex: number, colIndex: number, event: KeyboardEvent) => {
  event.preventDefault()
  console.log(`Row: ${rowIndex}, Col: ${colIndex} - Enter pressed`)
  if (rowIndex < pageSize.value - 1) {
    nextTick(() => {
      const nextInput = inputRefs.value?.[rowIndex + 1]?.[colIndex]?.$el?.querySelector('input')
      if (nextInput) {
        nextInput.focus()
        nextInput.select()
      }
    })
  } else {
    ElMessage.warning('您已到达当前页的最后一行，请翻页再继续')
  }
}

// Excel导入处理
const handleExcelImport = async (file: { raw: File }) => {
  try {
    // 清空原有数据
    sheetData.value = {}
    const workbook = new ExcelJS.Workbook()
    const buffer = await file.raw.arrayBuffer()
    await workbook.xlsx.load(buffer)

    workbook.eachSheet((worksheet, sheetId) => {
      const sheetName = worksheet.name
      const importedData: TableRow[] = []
      let headerRowNumber = 1; // 默认从第1行开始找
      // 遍历所有行，查找包含 "姓名" 或 "身份证" 的表头行
      worksheet.eachRow({ includeEmpty: false }, (row, rowNumber) => {
        const rowText = Array.isArray(row.values) ? row.values.map(v => String(v ?? '')).join('') : ''; // 合并整行文本
        if (rowText.includes("姓名") || rowText.includes("身份证")) {
          headerRowNumber = rowNumber;
          return false; // 找到后停止遍历
        }
      });
      const headerRow = worksheet.getRow(headerRowNumber);
      const columnMap: Record<string, number> = {};
      headerRow.eachCell((cell, colNumber) => {
        const columnName = cell.text?.trim() || ""; // 获取列名，如 "姓名"、"身份证号"
        columnMap[columnName] = colNumber;
      });
      worksheet.eachRow({ includeEmpty: false }, (row, rowNumber) => {
        if (rowNumber <= headerRowNumber) return; // 跳过表头及之前的行
        const rowData: TableRow = {
          index: rowNumber - 3,
          caseNumber: columnMap["案件编号"] ? row.getCell(columnMap["案件编号"]).text : '',
          boxNumber: columnMap["盒号"] ? row.getCell(columnMap["盒号"]).text : '',
          name: columnMap["姓名"] ? row.getCell(columnMap["姓名"]).text : '',
          idCard: columnMap["身份证"] ? row.getCell(columnMap["身份证"]).text : '',
          creationDate: columnMap["日期"] ? row.getCell(columnMap["日期"]).text : '',
          pageNumber: columnMap["页号"] ? row.getCell(columnMap["页号"]).text : '',
          itemNumber: columnMap["件号"] ? row.getCell(columnMap["件号"]).text : '',
          note: columnMap["备注"] ? row.getCell(columnMap["备注"]).text : '',
          title: columnMap["题名"] ? row.getCell(columnMap["题名"]).text : '',
          documentNumber: columnMap["文号"] ? row.getCell(columnMap["文号"]).text : '',
          socialSecurityCode: columnMap["社保编码"] ? row.getCell(columnMap["社保编码"]).text : '',
          socialSecurityUnit: columnMap["社保单位"] ? row.getCell(columnMap["社保单位"]).text : '',
          otherId: columnMap["其它身份证"] ? row.getCell(columnMap["其它身份证"]).text : '',
          responsibleParty: columnMap["责任人"] ? row.getCell(columnMap["责任人"]).text : '',
          pageCount: '',
          township: columnMap["乡镇"] ? row.getCell(columnMap["乡镇"]).text : '',
          hospital: columnMap["医院"] ? row.getCell(columnMap["医院"]).text : '',
        };
        importedData.push(rowData);
      });
      sheetData.value[sheetName] = importedData
      // 默认激活第一个sheet
      if (sheetId === 1) {
        activeSheet.value = sheetName
        console.log('导入数据:', sheetData)
        tableLength.value = importedData.length
      }
      updateAutoNumbers()
      showAlert('Excel导入成功！', 'success')
    });

  } catch (error) {
    showAlert(`Excel导入失败: ${error instanceof Error ? error.message : String(error)}`, 'error')
  }
}

// 更新自动编号
const updateAutoNumbers = () => {
  if (sheetData.value[activeSheet.value].length > 0) {
    const currentCaseNumber = sheetData.value[activeSheet.value][0].caseNumber || ''
    const currentBoxNumber = sheetData.value[activeSheet.value][0].boxNumber || ''
    let currentPageNumber = 1
    let currentItemNumber = 1
    let prevPage = ''

    sheetData.value[activeSheet.value].forEach((row) => {
      if (!row.caseNumber && currentCaseNumber) {
        row.caseNumber = currentCaseNumber
      }
      if (!row.boxNumber && currentBoxNumber) {
        row.boxNumber = currentBoxNumber
      }

      const pageKey = `${row.caseNumber}-${row.boxNumber}`
      if (pageKey !== prevPage) {
        currentPageNumber = 1
        currentItemNumber = 1
        prevPage = pageKey
      }

      if (!row.pageNumber) {
        row.pageNumber = padNumber(currentPageNumber, 3)
      }
      if (!row.itemNumber) {
        row.itemNumber = padNumber(currentItemNumber)
      }

      currentItemNumber++
      currentPageNumber++
    })
  }
}

// 切换排序方式
const toggleSort = (sheetName: string) => {
  if (!sheetData.value[sheetName]) return

  if (sortByBox.value) {
    sheetData.value[sheetName].sort((a, b) => {
      const boxDiff = parseInt(a.boxNumber) - parseInt(b.boxNumber)
      if (boxDiff !== 0) return boxDiff
      return parseInt(a.pageNumber) - parseInt(b.pageNumber)
    })
  } else {
    sheetData.value[sheetName].sort((a, b) => a.index - b.index)
  }
}

// 导出Excel
const doExportExcel = async () => {
  try {
    const workbook = new ExcelJS.Workbook()
    let postData: Array<any> = [];
    // 为每个sheet创建worksheet
    for (const [sheetName, data] of Object.entries(sheetData.value)) {
      const worksheet = workbook.addWorksheet(sheetName)
      // 1. 定义完整字段映射（保证顺序）
      const fieldMap = {
        title: '题名',
        documentNumber: '文号',
        creationDate: "形成日期",
        socialSecurityCode: '社保编码',
        socialSecurityUnit: '社保单位',
        caseNumber: "案件编号",
        boxNumber: "盒号",
        name: "姓名",
        idCard: "身份证",
        otherId: '其它身份证',
        responsibleParty: "责任人",
        itemNumber: "件号",
        pageNumber: "页号",
        pageCount: "页数",
        township: "乡镇",
        hospital: "医院",
        note: "备注"
      } as const;
      // 3. 设置列定义（含宽度和字体）
      worksheet.columns = Object.entries(fieldMap).map(([key, header]) => {
        // 根据内容类型设置不同列宽
        const widthMap: Record<string, number> = {
          '身份证': 25,
          '姓名': 12,
          '社保编码': 18,
          '备注': 30,
          '_default': 15
        };
        return {
          header,
          key,
          width: widthMap[header] || widthMap._default,
          style: {
            font: {
              name: 'Arial',
              size: 10
            }
          }
        };
      });
      const tableDataToSave = data.filter(item => item.name && item.idCard && item.creationDate);
      const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'))
      // 4. 添加数据行（带字体设置）
      tableDataToSave.forEach(item => {
        item.operatorId = userInfo.value.userId || null
        // 确保所有字段都有值
        const rowData = Object.keys(fieldMap).reduce((acc, key) => {
          acc[key] = item[key as keyof TableRow] || '';
          return acc;
        }, {} as Record<string, any>);
        // 添加行并设置字体
        const row = worksheet.addRow(rowData);
        row.font = { name: 'Arial', size: 10 };
        // 特殊字段处理
        if (item.idCard) {
          // 身份证号列设置为文本格式，避免科学计数法
          row.getCell('idCard').numFmt = '@';
        }
      });
      postData = postData.concat(tableDataToSave);
      // 5. 设置表头样式
      const headerRow = worksheet.getRow(1);
      headerRow.font = {
        name: 'Arial',
        size: 10,
        bold: true
      };
      headerRow.fill = {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: 'FFD9D9D9' } // 浅灰色背景
      };
    }
    // 6. 导出文件
    const fileName = `档案数据_${new Date().getTime()}.xlsx`;
    if (typeof window === 'undefined') {
      // Node环境
      await workbook.xlsx.writeFile(fileName);
    } else {
      // 浏览器环境
      const buffer = await workbook.xlsx.writeBuffer();
      saveAs(new Blob([buffer], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      }), fileName);
    }
    // 将数据保存到数据库
    try {
      const response = await postBatchMedicalRecords(postData);
      if (response) {
        showAlert('数据已成功保存到数据库', 'success');
      } else {
        showAlert('数据保存到数据库失败', 'error');
      }
    } catch (error) {
      showAlert(`数据保存到数据库失败: ${(error as Error).message}`, 'error');
    }
  } catch (error) {
    ElMessage.error(`导出失败: ${error instanceof Error ? error.message : String(error)}`);
    showAlert('导出失败，请检查数据格式', 'error');
  }
};

// 工具函数
const showAlert = (message: string, type: 'success' | 'error') => {
  alertMessage.value = message
  alertType.value = type
  setTimeout(() => {
    alertMessage.value = ''
  }, type === 'error' ? 5000 : 3000)
}

const padNumber = (num: number, length: number = 3): string => {
  return num.toString().padStart(length, '0')
}

const handleDelete = (index: number) => {
  sheetData.value[activeSheet.value].splice(index, 1);
  ElMessage.success('删除成功');
};

const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event)
}

// 获取指定sheet的过滤后数据
const getFilteredData = (sheetName: string) => {
  const data = sheetData.value[sheetName] || []
  return data.filter(item =>
    item.name.includes(searchForm.value.searchName) &&
    item.idCard.includes(searchForm.value.searchIdCard)
  )
};

// 获取分页数据
const getPagedData = (sheetName: string) => {
  const filtered = getFilteredData(sheetName)
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filtered.slice(start, end)
}

// 获取过滤后的数据量
const getFilteredCount = (sheetName: string) => {
  return getFilteredData(sheetName).length
}

// 获取表格统计信息
const getTableLength = (sheetName: string) => {
  const data = sheetData.value[sheetName] || []
  const validCount = data.filter(item => item.name && item.idCard).length
  return data.length > 0 ? `共 ${data.length} 条记录，有效数据 ${validCount} 条` : ''
}
</script>

<style scoped>
.container {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-actions {
  display: flex;
  align-items: center;
  gap: 20px;
}

.upload-demo {
  display: inline-block;
}

.tips {
  font-size: 12px;
  color: #909399;
}
</style>